/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/


#include "MkHttp/MkHttpClient.h"
#include "MkHttp/MkHttpResponse.h"
#include "MkEvent/MkEvent.h"
#include "MkEvent/MkEventPool.h"
#include "MkEvent/MkTimer.h"
#include <MkUtil/MkLog.h>
#include <signal.h>
#include <MkUtil/MkBase64.h>

MkVector<CMkEvent *> VecEvent;
BOOL g_bRun = TRUE;
void SigHandle(int sig)
{
    if (sig == SIGINT) {
        g_bRun = FALSE;
    }
};

int main(int argc, char ** argv)
{
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    //signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
    //signal(SIGPIPE, SIG_IGN);
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGPIPE);
    sigprocmask(SIG_BLOCK, &set, NULL);
#endif
    //MkLogInitLevel("http_client", TO_FILE);
    MkLogChangeLevel(LOG_DEBUG);
    signal(SIGINT, SigHandle);// 设置退出信号
    CMkEventPool Pool;
    Pool.Start(1);
    CMkTimer Timer;
    Timer.StartTimerThread();
    //MkMap<MkString, MkString> MapHeader;
    //MapHeader["Authorization"] = "Basic YWRtaW46YWRtaW4=";

    MkString Url = "http://192.168.100.120:58090/api/v1/version";
    Url = "http://192.168.100.25:7480/pic/blur/1687715911304454146404.jpg";
    Url = "http://192.168.0.24/api/v1/version";

    while (g_bRun) {
        CMkHttpClient  *pClient = new  CMkHttpClient(Pool.GetFreeEvent(), &Timer, [](CMkTcpClient  *pClient) {   
            MkDebugLog("delete pclient:%p\n", pClient);
            MkDelete(pClient);
        });
        pClient->SendRequest(MkHttpMethodGet, Url, MkMapString(), MkString(), MkMapString(), [](const MkHttpStatusCode& StatusCode, const MkString& Res) {
            MkDebugLog("http response:%d\n", StatusCode);
        }, 3000);
        CMkThread::ThreadSleep(200000);
    }
    Timer.StopTimerThread();
    Pool.Stop();
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}

